<style lang="less">
.detail-list-line .label.default{
  color: #333;
  padding:6px 0 0;
}
</style>
<template>
<div class="detail-list">
  <div class="loader-base" v-if="showLoad"><div class="loader-wrap"></div></div>
  <div class="detail-list-line displayflex">
    <div class="label default flex1">{{txt}}
      <template v-if="isAndroid && reiImg">（建议每张图片只含有一张发票内容）</template>
    </div>
  </div>
  <div class="add-pic cf">
    <template  v-for="(item, index) in attaches">
      <div class="img f-l">
        <i class="removePic iconfont icon-close1" @click="removePic(1, index)"></i>
        <img class="qs-indicator" :src="item.url | fileImg" @click="previewPic(index)">
      </div>
    </template>
    <template  v-for="(item, index) in imgListBase" v-if="!isAndroid">
      <div class="img f-l">
        <i class="removePic iconfont icon-close1" @click="removePic(2, index)"></i>
        <img class="qs-indicator" :src="item" @click="previewPic(attaches.length + index)">
      </div>
    </template>
    <template v-for="(item, index) in imgIds" v-if="isAndroid">
      <div class="img f-l">
        <i class="removePic iconfont icon-close1" @click="removePic(2, index)"></i>
        <img class="qs-indicator" :src="item" @click="wxpreviewPic(item)">
      </div>
    </template>
    <div class="btn f-l" @click="getImage()"></div>
  </div>
  <previewer :list="imgPre" :options="options" ref="previewer"></previewer>
  <!-- <img :src="testlocalId[0]"> -->
</div>
</template>

<script>
  export default {
    props:{
      attaches: Array,
      txt: {
        type: String,
        default: '电子附件'
      },
      reiImg:{
        type:Boolean,
        default:false
      }
    },
    data(){
      return {
        imgIds:[],
        imgListBase:[],
        showLoad:false,
        imgPre:[],
        options: {
          getThumbBoundsFn (index) {
            let thumbnail = document.querySelectorAll('.qs-indicator')[index]
            let pageYScroll = window.pageYOffset || document.documentElement.scrollTop
            let rect = thumbnail.getBoundingClientRect()
            return {x: rect.left, y: rect.top + pageYScroll, w: rect.width}
          }
        },
        isAndroid:false,

        // testlocalId:'',
      }
    },
    created(){
      var u = navigator.userAgent.toLowerCase();
      var isAndroid = u.indexOf('android') > -1; //android终端
      this.isAndroid = isAndroid;
    },
    watch:{
      attaches:{
        handler(newVal,oldVal){
          this.setPreList().then((args) => {
            this.imgPre = args;
            // console.log(this.imgPre)
          })
          .catch(() => { this.imgPre = [] });
        },
        deep:true
      },
      imgListBase:{
        handler(newVal,oldVal){
          this.setPreList().then((args) => {
            this.imgPre = args;
            // console.log(this.imgPre)
          })
          .catch(() => { this.imgPre = [] });
        },
        deep:true
      }
    },
    mounted(){
      
    },
    methods:{
      // aaa(id){
      //   var _this = this;
      //   this.jWeixin.uploadImage({
      //     localId: id, // 需要上传的图片的本地ID，由chooseImage接口获得
      //     isShowProgressTips: 1, // 默认为1，显示进度提示
      //     success: function (res) {
      //       alert("uploadImage")
      //       var serverId = res.serverId; // 返回图片的服务器端ID
      //       _this.bbb(serverId)
      //     }
      //   });
      // },
      // bbb(id){
      //   alert(id+"微信服务器id")
      //   var _this = this;
      //   this.jWeixin.downloadImage({
      //     serverId: id, // 需要下载的图片的服务器端ID，由uploadImage接口获得
      //     isShowProgressTips: 1, // 默认为1，显示进度提示
      //     success: function (res) {
      //       var localId = res.localId; // 返回图片下载后的本地ID
      //       _this.testlocalId = localId;
      //     }
      //   });
      // },
      //微信接口预览-针对安卓
      wxpreviewPic(id){
        var _this = this;
        this.jWeixin.previewImage({
          current: id, // 当前显示图片的http链接
          urls: _this.imgIds // 需要预览的图片http链接列表
        });
      },
      //获取选择的图片id
      getImage() {
        var self = this;
        let currentSize = this.imgListBase.length;
        if (currentSize + this.attaches.length == 9) {
          self.$vux.toast.show({
            type: "text", //success, warn, cancel, text
            text: "最多上传9张图片"
          });
          return false;
        } else {
          //this.imgListBase.push('')
          // this.imgListBase.push('')
          // this.$emit("getImgArr", this.imgListBase);

          var attachesLength = self.attaches?self.attaches.length:0;
          self.jWeixin.chooseImage({
            count: 9 - attachesLength - currentSize, // 默认9
            sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
            sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有
            success: function(res) {
              // alert(JSON.stringify(res)+"，微信chooseImage")
              var localIds = res.localIds; 
              // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
              if (attachesLength + localIds.length + self.imgListBase.length > 9) {
                self.$vux.toast.show({
                  type: "text", //success, warn, cancel, text
                  text: "最多上传9张图片"
                });
                return false;
              };
              localIds.forEach(i => {
                self.imgIds.push(i);
              });
              self.imgIds = Array.from(new Set(self.imgIds));
              // self.aaa(self.imgIds[0])
              self.getLocalImgData(currentSize);
            }
          });
          // alert(JSON.stringify(self.imgIds))
        }
      },

      //获取图片的base64
      getLocalImgData(index) {
        var self = this;
        this.showLoad = true;
        if(self.imgIds[index]){
          this.jWeixin.getLocalImgData({
            localId: self.imgIds[index], // 图片的localID
            success: function(res) {
              let localData = res.localData;
              if (window.__wxjs_is_wkwebview) {
                self.imgListBase.push(localData);
              } else {
                var imgbase64 = 'data:image/png;base64,'+ localData;
                self.imgListBase.push(imgbase64);
              };
              self.$emit("getImgArr", self.imgListBase);
              self.getLocalImgData(index + 1);
            }
          });
          // console.log(self.imgListBase[0],"@@")
        } else {
          self.showLoad = false;
        }
      },

      resetImgListBase(){
        this.imgListBase = [];
        this.imgIds = [];
      },

      previewPic(index){
        this.$refs.previewer.show(index);
      },

      setPreList(){
        return new Promise((resolve, reject) => {
          let arr = this.attaches.concat(this.imgListBase),
              args = [],
              te = this.$options.filters['fileImg'];
          arr.forEach((item)=> {
            let preItem = item;
            if(JSON.stringify(item).indexOf('base64') < 0) preItem = te(item.url);
            let column = { msrc : preItem, src : preItem };
            args.push(column);
          });

          if(args.length > 0)
          {
            resolve(args);
          }
          else
          {
            reject('error');
          }
        })
      },

      removePic(type, index) {
        if(type == 1) {
          this.attaches.splice(index,1);
        }
        if(type == 2) {
          this.imgListBase.splice(index,1);
          this.imgIds.splice(index,1);
        }
        
      },
    }
  }
</script>